package com.web.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by xukk on 2017/6/5.
 */
@Slf4j
@Service
public class SecurityMetadataSourceService implements FilterInvocationSecurityMetadataSource {

    private static Map<String, Collection<ConfigAttribute>> resourceMap = null;

    public static void clearCache(){
        resourceMap=null;
    }
    /**
     * ApplicationContext ctx =  WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
     * CustomInvocationSecurityMetadataSource cs=(CustomInvocationSecurityMetadataSource)ctx.getBean("customSecurityMetadataSource",com.zst.meadow.security.CustomInvocationSecurityMetadataSource.class);
     * cs.loadResourceDefine();
     * 加载所有角色与权限的关系
     */
    private void loadAllResources() {
        if (resourceMap == null) {
        }
    }

    /**
     * 返回所请求资源所需要的权限,根据roleName得到模块
     */
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        if (resourceMap == null) {
            loadAllResources();
        }
        HttpServletRequest request = ((FilterInvocation) object).getHttpRequest();
        AntPathRequestMatcher matcher;
        String resUrl;
        if(resourceMap!=null)
        for (Iterator<String> iter = resourceMap.keySet().iterator(); iter.hasNext(); ) {
            resUrl = iter.next();
            matcher = new AntPathRequestMatcher(resUrl);
            if (matcher.matches(request)) {
                return resourceMap.get(resUrl);
            }
        }
        return null;
    }

    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    public boolean supports(Class<?> clazz) {
        return true;
    }
}
